import { postAuth } from "../http";
import { AGENT_BACKEND_API_KEY } from "../auth";

// 定义请求体的接口
interface EmbeddingRequest {
    input: string;
    model: string;
}

// 定义响应体的接口
export interface EmbeddingResponse {
    object: string;
    data: {
        object: string;
        embedding: number[];
        index: number;
    }[];
    model: string;
    usage: {
        prompt_tokens: number;
        total_tokens: number;
    };
}
/**
 * 获取文本的嵌入向量
 * @param text 文本
 * @returns
 */
export async function getTextEmbedding(
    request: EmbeddingRequest,
    apiKey?: string
): Promise<EmbeddingResponse> {
    const key = apiKey ?? AGENT_BACKEND_API_KEY;
    if (!key) {
        throw new Error("API key is missing");
    }
    const requestBody = {
        input: request.input,
        model: request.model
    };
    try {
        const response = await postAuth<EmbeddingResponse>(
            "https://api.openai.com/v1/embeddings",
            requestBody,
            key
        );

        if (response.status === 200) {
            return response.data;
        } else {
            console.error(`Unexpected response status: ${response.status}`);
            throw new Error("Failed to get embedding");
        }
    } catch (error) {
        console.error("Error in getting embedding:", error);
        throw error;
    }
}